package com.define.ssh.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.define.ssh.model.Func;
import com.define.ssh.util.SystemUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/* 权限验证拦截器 */
@SuppressWarnings("serial")
public class PermissionInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log LOG = LogFactory
			.getLog(PermissionInterceptor.class);

	/** 拦截请求并进行登录有效性验证 */
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		final HttpServletRequest request = ServletActionContext.getRequest();
		// 取得请求的URL
		String url = request.getRequestURL().toString();
		int len=0;
		if(request.getContextPath()!=null&&!request.getContextPath().equalsIgnoreCase("")){
			len=url.indexOf(request.getContextPath())+request.getContextPath().length();
		}else
		{
			url = request.getRequestURI().toString();
		}
		
		final HttpServletResponse response = ServletActionContext.getResponse();
		
		url = url.substring(len, url.lastIndexOf("!"));  		
		if(commonPath(url)){
			return ai.invoke();
		}else{
			if(this.permission(url)){
				return ai.invoke();
			}else{
				return "noAuth";
			}
		}
	}
	
	private boolean permission(String path){
		List<Func> funcList =(List<Func>) ServletActionContext
				.getRequest().getSession()
				.getAttribute(SystemUtil.FUNCTIONlIST);
		if(funcList!=null&&funcList.size()>0){
			for(Func func:funcList){
				if(func.getUrl().contains(path)){
					return true;
				}
		 }
		}
		return false;
	}
	
	private boolean commonPath(String nowpath){
		List<String> pathList=new ArrayList<String>();
		pathList.add("/admin/login!checkLogin.xhtml");
		pathList.add("/admin/logout!logout.xhtml");
		for(String p:pathList){
			if(p.contains(nowpath)){
				return true;
			}
		}
		return false;
	}
}